<script setup lang="ts">
import Tools from '@/utils/tools';
import HomeRequest from '@/request/homeRequest';
import useToast from '@/hooks/useToast';

interface IProps {
  variantId: string;
}

interface IState {
  show: boolean;
  calendarShow: boolean;
  availSvcPer: IObtainServerWaiterRelationRes[];
  columns: Array<{ values: string[]; defaultIndex?: number }>;
  timeRanges?: Record<string, Record<number, string[]>>;
  resultTime: string;
}

type EmitEvents = {
  (event: 'change', payload: string): void;
};

const props = defineProps<IProps>();
const state = reactive<IState>({ calendarShow: false, show: false, availSvcPer: [], columns: [], resultTime: '' });
const emits = defineEmits<EmitEvents>();
const { showToast } = useToast();

// 日历选择完成
const handleCalendarConfir = (e: any) => {
  const date = Tools.formatTimeStringToDate(e.detail);
  HomeRequest.ObtainServerWaiterRelation({ date, variantId: props.variantId, hasLoading: true }).then((res) => {
    if (res.data) {
      state.calendarShow = false;
      state.resultTime = date;
      generateTimeIntervals(res.data);
    } else {
      showToast(`${date} 没有可服务时间`);
    }
  });
};

// 将时间段数组转换为详细时间点的对象
function generateTimeIntervals(intervals: IObtainServerWaiterRelationRes[]) {
  const result: Record<string, Record<number, string[]>> = {};
  intervals.forEach(({ begin, end }) => {
    const timeGroups: Record<number, string[]> = {};
    let current = new Date(`1970-01-01T${begin}:00`);
    const endTime = new Date(`1970-01-01T${end}:00`);

    while (current <= endTime) {
      const hours = current.getHours();
      const minutes = String(current.getMinutes()).padStart(2, '0');
      if (!timeGroups[hours]) {
        timeGroups[hours] = [];
      }
      timeGroups[hours].push(minutes);
      current.setMinutes(current.getMinutes() + 1);
    }

    const rangeKey = `${begin} ~ ${end}`;
    result[rangeKey] = timeGroups;
  });
  state.timeRanges = result;
  state.columns = [{ values: Object.keys(result) }, { values: Object.keys(result[Object.keys(result)[0]]) }, { values: result[Object.keys(result)[0]][Number(Object.keys(result)[0].substring(0, 2))] }];
  state.show = true;
}

// 选择弃change事件处理
const handlePickerChange = (event: any) => {
  const { picker, value, index } = event.detail;
  if (index === 0) {
    picker.setColumnValues(1, Object.keys(state.timeRanges![value[0]]));
    picker.setColumnValues(2, state.timeRanges![value[0]][Number(Object.keys(state.timeRanges![value[0]])[0])]);
  }
  if (index === 1) {
    picker.setColumnValues(2, state.timeRanges![value[0]][value[1]]);
  }
};

// 选择器选中事件
const handlePickerConfirm = (event: any) => {
  state.resultTime += ` ${event.detail.value[1]}:${event.detail.value[2]}`;
  console.log(state.resultTime);
  emits('change', state.resultTime);
  state.show = false;
};
</script>

<template>
  <view class="flex justify-between mt-12px text-red" @click="state.calendarShow = true">
    <text>服务时间：</text>
    <view class="flex items-center">
      <text>{{ state.resultTime.length > 11 ? state.resultTime : '请选择' }}</text>
      <i class="i-icon-park-outline:right ml-4px"></i>
    </view>
  </view>

  <van-popup position="bottom" round :show="state.show" @close="state.show = false">
    <van-picker show-toolbar value-key="text" :columns="state.columns" title="请选择具体的服务时间" @cancel="state.show = false" @change="handlePickerChange" @confirm="handlePickerConfirm" />
  </van-popup>

  <van-calendar :show="state.calendarShow" :color="'#ffc300'" @close="state.calendarShow = false" @confirm="handleCalendarConfir" />
</template>
